package com.czhoujunlv.drug.fragment;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.util.ArrayMap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.czhoujunlv.drug.Bean.Goods_data;
import com.czhoujunlv.drug.Bean.ModelHomeEntrance;
import com.czhoujunlv.drug.Bean.SearchData;
import com.czhoujunlv.drug.Bean.SearchData2;
import com.czhoujunlv.drug.Bean.Shop_goods;
import com.czhoujunlv.drug.HeadPage;
import com.czhoujunlv.drug.MainActivity;
import com.czhoujunlv.drug.R;
import com.czhoujunlv.drug.adapter.CagegoryViewPagerAdapter;
import com.czhoujunlv.drug.adapter.EntranceAdapter;
import com.czhoujunlv.drug.scorllview.AnimationNestedScrollView;
import com.czhoujunlv.drug.scorllview.CommonUtil;
import com.czhoujunlv.drug.toolclass.IndicatorView;
import com.czhoujunlv.drug.toolclass.ItemUtil;
import com.czhoujunlv.drug.toolclass.RoundImageView;
import com.czhoujunlv.drug.toolclass.ScreenUtil;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.refactor.lib.colordialog.ColorDialog;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;

public class HeadFragment extends Fragment {

    private AnimationNestedScrollView sv_view;
    private ConstraintLayout ll_search,flow_llay,flow_llay2;
    private TextView tv_title;
    private ImageView img,find,saoyisao,back;
    private Banner banner;
    private float LL_SEARCH_MIN_TOP_MARGIN, LL_SEARCH_MAX_TOP_MARGIN, LL_SEARCH_MAX_WIDTH, LL_SEARCH_MIN_WIDTH, TV_TITLE_MAX_TOP_MARGIN;
    private float title_margin_top;
    private ViewGroup.MarginLayoutParams searchLayoutParams, titleLayoutParams,imgLayoutParams;
    public static final int HOME_ENTRANCE_PAGE_SIZE = 10;//首页菜单单页显示数量
    private ViewPager entranceViewPager;
    private ConstraintLayout homeEntranceLayout;
    private List<ModelHomeEntrance> homeEntrances;
    private LinearLayout pointLinearLayout;
    private List<ImageView> points;
    private List<View> viewList;
    static String token;
    List<SearchData2> searchList;
    private EditText findText;
    List<Goods_data> list = new ArrayList<>();
    String[] category = {"首页","家庭常备","男科中心","母婴乐园","老年中心","美肤商城", "滋补保健","性福生活","器械商城","美妆个护"};
    List<String> listCategory = new ArrayList<>();
    private RecyclerView FenLei,goods,search;
    public final static int CONNECT_TIMEOUT = 60;
    public final static int READ_TIMEOUT = 100;
    public final static int WRITE_TIMEOUT = 60;
    public static final OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
            .build();
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_headfragment, container, false);
        ScreenUtil.init(getActivity());
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user",getActivity().MODE_PRIVATE);
        token = sharedPreferences.getString("token",null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initData();
        initView();//初始化控件
        searchLayoutParams = (ViewGroup.MarginLayoutParams) ll_search.getLayoutParams();
        titleLayoutParams = (ViewGroup.MarginLayoutParams) tv_title.getLayoutParams();
        imgLayoutParams = (ViewGroup.MarginLayoutParams) img.getLayoutParams();
        top_scorll();//顶部滑动效果
        bannerView();
        init();
        final Thread thread = new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    String res = post1("http://192.168.43.138:8080/index/selectedGood","1");
                    Gson gson = new Gson();
                    Shop_goods shop_goods = gson.fromJson(res, Shop_goods.class);
                    list.clear();
                    for (int i = 0; i < shop_goods.getData().size(); i++) {
                        Goods_data goods_data = new Goods_data();
                        goods_data.img = shop_goods.getData().get(i).getImg();
                        goods_data.brade = shop_goods.getData().get(i).getBrand();
                        goods_data.name = shop_goods.getData().get(i).getName();
                        goods_data.des = shop_goods.getData().get(i).getDescription();
                        goods_data.price = String.valueOf(shop_goods.getData().get(i).getSaleMoney());
                        goods_data.standard = shop_goods.getData().get(i).getStandards();
                        goods_data.companyId = shop_goods.getData().get(i).getCompanyId();
                        goods_data.id = shop_goods.getData().get(i).getId();
                        list.add(goods_data);
                        Log.i("list大小：", String.valueOf(list.size()));
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            goods.setAdapter(new MyAdapter());
                            goods.setLayoutManager(new GridLayoutManager(getActivity(), 2));
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();

        listCategory.clear();
        for (int i =0 ; i <category.length;i++){

            listCategory.add(category[i]);
            Log.i("个数：",String.valueOf(listCategory.size()));
        }
        FenLei.setAdapter(new MyAdapter2());
        FenLei.setLayoutManager(new LinearLayoutManager(getActivity(),RecyclerView.HORIZONTAL,false));
        find.setOnClickListener(new View.OnClickListener() {//搜索药品
            @Override
            public void onClick(View v) {
                sv_view.setVisibility(View.GONE);
                search.setVisibility(View.VISIBLE);
                Thread thread1 = new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        try {
                            String s = getSearch("http://192.168.43.138:8080/index/getGoodBySearch/"+ findText.getText().toString());
                            Gson gson = new Gson();
                            SearchData searchData = gson.fromJson(s,SearchData.class);
                            searchList = new ArrayList<>();
                            searchList.clear();
                            for(int i =0 ;i <searchData.getData().size();i++){
                                SearchData2 searchData2 = new SearchData2();
                                searchData2.brand = searchData.getData().get(i).getBrand();
                                searchData2.name = searchData.getData().get(i).getName();
                                searchData2.description = searchData.getData().get(i).getDescription();
                                searchData2.saleMoney = searchData.getData().get(i).getSale_money();
                                searchData2.img = searchData.getData().get(i).getImg();
                                searchList.add(searchData2);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                search.setAdapter(new SearchAdapter());
                                search.setLayoutManager(new LinearLayoutManager(getActivity()));
                            }
                        });
                    }
                };
                thread1.start();

            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sv_view.setVisibility(View.VISIBLE);//可见
                search.setVisibility(View.GONE);
            }
        });
        saoyisao.setOnClickListener(new View.OnClickListener() {//扫一扫
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
                //请求权限
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
                Intent intent = new Intent(getActivity(), CaptureActivity.class);

                ZxingConfig config = new ZxingConfig();
                config.setPlayBeep(true);//是否播放扫描声音 默认为true
                config.setShake(true);//是否震动  默认为true
                config.setDecodeBarCode(true);//是否扫描条形码 默认为true
                config.setReactColor(R.color.colorAccent);//设置扫描框四个角的颜色 默认为白色
                config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
                config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色
                config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                startActivityForResult(intent,111);
                onActivityResult(111,RESULT_OK,intent);
            }
        });

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 扫描二维码/条码回传
        if (requestCode == 111 && resultCode == RESULT_OK) {
            if (data != null) {

                String content = data.getStringExtra(Constant.CODED_CONTENT);
                Toast.makeText(getActivity(),"扫描结果："+content,Toast.LENGTH_LONG).show();
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(content);//此处填链接
                intent.setData(content_url);
                startActivity(intent);
            }
        }
    }

    private void initView() {//控件的初始化
        sv_view = getActivity().findViewById(R.id.search_sv_view);
        ll_search = getActivity().findViewById(R.id.search_ll_search);
        tv_title = getActivity().findViewById(R.id.search_tv_title);
        img = getActivity().findViewById(R.id.img);
        banner = getActivity().findViewById(R.id.banner);
        find = getActivity().findViewById(R.id.imageView3);
        findText = getActivity().findViewById(R.id.find);
        saoyisao = getActivity().findViewById(R.id.imageView);
        back = getActivity().findViewById(R.id.imageView21);
        search = getActivity().findViewById(R.id.search_result);

        homeEntranceLayout = (ConstraintLayout) getActivity().findViewById(R.id.home_entrance);
        entranceViewPager = (ViewPager) getActivity().findViewById(R.id.main_home_entrance_vp);
        pointLinearLayout = (LinearLayout) getActivity().findViewById(R.id.point);

        flow_llay2 = getActivity().findViewById(R.id.flow_llay2);
        flow_llay = getActivity().findViewById(R.id.flow_llay);

        FenLei = getActivity().findViewById(R.id.FenLei);
        goods = getActivity().findViewById(R.id.goods);

    }


    private void initData() {
        homeEntrances = new ArrayList<>();
        homeEntrances.add(new ModelHomeEntrance("潇湘超市", R.mipmap.ic_category_0));
        homeEntrances.add(new ModelHomeEntrance("医疗设备", R.mipmap.ic_category_1));
        homeEntrances.add(new ModelHomeEntrance("潮流医学", R.mipmap.ic_category_2));
        homeEntrances.add(new ModelHomeEntrance("生活服务", R.mipmap.ic_category_3));
        homeEntrances.add(new ModelHomeEntrance("潇湘到家", R.mipmap.ic_category_4));
        homeEntrances.add(new ModelHomeEntrance("潇湘充值", R.mipmap.ic_category_5));
        homeEntrances.add(new ModelHomeEntrance("现金福利", R.mipmap.ic_category_6));
        homeEntrances.add(new ModelHomeEntrance("领券", R.mipmap.ic_category_7));
        homeEntrances.add(new ModelHomeEntrance("领金贴", R.mipmap.ic_category_8));
        homeEntrances.add(new ModelHomeEntrance("潇湘会员", R.mipmap.ic_category_10));
        homeEntrances.add(new ModelHomeEntrance("潇湘国际", R.mipmap.ic_category_11));
        homeEntrances.add(new ModelHomeEntrance("潇湘拍卖", R.mipmap.ic_category_12));
        homeEntrances.add(new ModelHomeEntrance("潇湘看病", R.mipmap.ic_category_13));
        homeEntrances.add(new ModelHomeEntrance("潇湘二手", R.mipmap.ic_category_14));
        homeEntrances.add(new ModelHomeEntrance("潇湘旅行", R.mipmap.ic_category_16));
        homeEntrances.add(new ModelHomeEntrance("全部分类", R.mipmap.ic_category_15));
    }
    private void init() {//viewpager和指示器
        ConstraintLayout.LayoutParams layoutParams12 = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.CHAIN_SPREAD, (int) ((float) ScreenUtil.getScreenWidth() / 3.0f));

        //首页菜单分页
        //ConstraintLayout.LayoutParams entrancelayoutParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, (int) ((float) ScreenUtil.getScreenWidth() / 4.0f + 70));
        //homeEntranceLayout.setLayoutParams(entrancelayoutParams);

        entranceViewPager.setLayoutParams(layoutParams12);
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        //将RecyclerView放至ViewPager中：
        int pageSize = HOME_ENTRANCE_PAGE_SIZE;
        //一共的页数等于 总数/每页数量，并取整。
        int pageCount = (int) Math.ceil(homeEntrances.size() * 1.0 / pageSize);
        viewList = new ArrayList<View>();
        for (int index = 0; index < pageCount; index++) {
            //每个页面都是inflate出一个新实例
            RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.item_home_entrance_vp, entranceViewPager, false);
            recyclerView.setLayoutParams(layoutParams12);

            recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 5));
            EntranceAdapter entranceAdapter = new EntranceAdapter(getActivity(), homeEntrances, index, HOME_ENTRANCE_PAGE_SIZE);
            recyclerView.setAdapter(entranceAdapter);
            viewList.add(recyclerView);
        }
        CagegoryViewPagerAdapter adapter = new CagegoryViewPagerAdapter(viewList);
        entranceViewPager.setAdapter(adapter);

        points = new ArrayList<>();
        Log.i("RecyclerView的数量：", String.valueOf(viewList.size()));
        initPoint();
        entranceViewPager.setCurrentItem(0);
        entranceViewPager.clearOnPageChangeListeners();

        entranceViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for(int i=0;i<points.size();i++){
                    points.get(i).setImageResource(R.drawable.unselect_point);
                }
                points.get(position).setImageResource(R.drawable.select_point);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
//        entranceIndicatorView.setIndicatorCount(entranceViewPager.getAdapter().getCount());
//        entranceIndicatorView.setCurrentIndicator(entranceViewPager.getCurrentItem());
//        entranceViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
//            @Override
//            public void onPageSelected(int position) {
//                entranceIndicatorView.setCurrentIndicator(position);
//            }
//        });
    }
    public void initPoint(){//指示器小圆点
        for(int i =0 ;i<viewList.size();i++) {
            ImageView point = new ImageView(getActivity());
            point.setImageResource(R.drawable.unselect_point);
            point.setLayoutParams(new LinearLayout.LayoutParams(30,30));
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) point.getLayoutParams();
            lp.setMargins(0,0,0,0);
            points.add(point);
            pointLinearLayout.addView(point);
        }
        points.get(0).setImageResource(R.drawable.select_point);
    }
    private void bannerView(){//轮播图
        List<Integer> images = new ArrayList<>();
        images.add(R.drawable.a);
        images.add(R.drawable.b);
        images.add(R.drawable.c);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置图片加载器
        banner.setImageLoader(new HeadFragment.GlideImageLoader());
        //设置图片集合
        banner.setImages(images);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(2000);
        //小点点居中
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();

    }
    public class GlideImageLoader extends ImageLoader {//图片加载器
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            imageView.setImageResource((Integer) path);
        }
        /**
         * 自定义圆角类
         * @param context
         * @return
         */
        @Override
        public ImageView createImageView(Context context) {
            RoundImageView img = new RoundImageView(context);
            return img;

        }
    }
    private void top_scorll(){//滑动事件监听
        LL_SEARCH_MIN_TOP_MARGIN = CommonUtil.dp2px(getActivity(), 4.5f);//布局关闭时顶部距离
        LL_SEARCH_MAX_TOP_MARGIN = CommonUtil.dp2px(getActivity(),49f);//布局默认展开时顶部距离
        LL_SEARCH_MAX_WIDTH = CommonUtil.getScreenWidth(getActivity())- CommonUtil.dp2px(getActivity(), 30f);//布局默认展开时的宽度
        LL_SEARCH_MIN_WIDTH = CommonUtil.getScreenWidth(getActivity()) - CommonUtil.dp2px(getActivity(), 120f);//布局关闭时的宽度
        TV_TITLE_MAX_TOP_MARGIN = CommonUtil.dp2px(getActivity(), 11.5f);
        title_margin_top = CommonUtil.dp2px(getActivity(),245f);

        sv_view.setOnAnimationScrollListener(new AnimationNestedScrollView.OnAnimationScrollChangeListener() {
            @Override
            public void onScrollChanged(float dy) {
                float searchLayoutNewTopMargin = LL_SEARCH_MAX_TOP_MARGIN - dy;
                float searchLayoutNewWidth = LL_SEARCH_MAX_WIDTH - dy * 2.4f;//此处 * 1.3f 可以设置搜索框宽度缩放的速率

                float titleNewTopMargin = (float) (TV_TITLE_MAX_TOP_MARGIN - dy * 0.5);

                //处理布局的边界问题
                searchLayoutNewWidth = searchLayoutNewWidth < LL_SEARCH_MIN_WIDTH ? LL_SEARCH_MIN_WIDTH : searchLayoutNewWidth;

                if (searchLayoutNewTopMargin < LL_SEARCH_MIN_TOP_MARGIN) {
                    searchLayoutNewTopMargin = LL_SEARCH_MIN_TOP_MARGIN;
                }

                if (searchLayoutNewWidth < LL_SEARCH_MIN_WIDTH) {
                    searchLayoutNewWidth = LL_SEARCH_MIN_WIDTH;
                }

                if(flow_llay2 != null) {
                    if(dy >= title_margin_top) {
                        flow_llay.setVisibility(View.VISIBLE);
                    } else {
                        flow_llay.setVisibility(View.GONE);
                    }
                }

                float titleAlpha = 255 * titleNewTopMargin / TV_TITLE_MAX_TOP_MARGIN;
                if (titleAlpha < 0) {
                    titleAlpha = 0;
                }

                //设置相关控件的LayoutParams  此处使用的是MarginLayoutParams，便于设置params的topMargin属性
                tv_title.setTextColor(tv_title.getTextColors().withAlpha((int) titleAlpha));
                titleLayoutParams.topMargin = (int) titleNewTopMargin;
                tv_title.setLayoutParams(titleLayoutParams);

                img.setColorFilter(img.getSolidColor());
                imgLayoutParams.topMargin = (int) titleNewTopMargin;
                img.setLayoutParams(imgLayoutParams);

                searchLayoutParams.topMargin = (int) searchLayoutNewTopMargin;
                searchLayoutParams.width = (int) searchLayoutNewWidth;
                ll_search.setLayoutParams(searchLayoutParams);
            }
        });
    }

    public class MyAdapter extends RecyclerView.Adapter<MyHolder>{//商品的RecyclerView适配器

        @NonNull
        @Override
        public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.goods_item,parent,false);
            MyHolder myHolder = new MyHolder(view);
            return myHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull final MyHolder holder, int position) {
            if (position % 2 == 0) {//RecyclerView均匀排列
                ItemUtil.setViewMargin(holder.itemView, false, 12, 6, 12, 0);
            } else {
                ItemUtil.setViewMargin(holder.itemView, false, 6, 12, 12, 0);
            }
            final Goods_data data = list.get(position);
            Glide.with(getActivity()).load(data.getImg()).into(holder.img);
            holder.shop.setText(" "+data.getBrade()+" ");
            holder.name.setText(data.getName());
            holder.describe.setText(data.getDes());
            holder.price.setText(data.getPrice());
            holder.standard.setText(data.getStandard());
            holder.itemView.setOnClickListener(new View.OnClickListener() {//item的点击
                @Override
                public void onClick(View v) {//点击出现弹窗
                    ColorDialog dialog = new ColorDialog(getActivity());
                    dialog.setTitle(holder.name.getText());
                    dialog.setContentText(holder.describe.getText());
                    dialog.setColor("#2b4490");
                    dialog.setContentImage(holder.img.getDrawable());
                    dialog.setPositiveListener("加入购物车", new ColorDialog.OnPositiveListener() {
                        @Override
                        public void onClick(ColorDialog dialog) {
                            Toast.makeText(getActivity(), dialog.getNegativeText().toString(), Toast.LENGTH_SHORT).show();
                            final String json = "{"+"\"businessId\":"+data.getCompanyId()+"," + "\"consumerId\":"+ 1 +
                                    ",\"goodId\":"+data.getId()+
                                    ",\"number\":"+ 1 +
                                    ",\"time\":\"2020-12-23 11:11:11\"" +
                                    "}";
                            Thread thread = new Thread(){
                                @Override
                                public void run() {
                                    super.run();
                                    try {
                                        if(token!=null) {
                                            String s = post("http://192.168.43.138:8080/index/addShopGood", json);
                                            Log.i("添加状态的token：", token);
                                        }else{
                                            Toast.makeText(getActivity(),"请先登录",Toast.LENGTH_SHORT).show();
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            };
                            thread.start();

                            dialog.dismiss();
                        }
                    }).setNegativeListener("取消", new ColorDialog.OnNegativeListener() {
                                @Override
                                public void onClick(ColorDialog dialog) {
                                    Toast.makeText(getActivity(), dialog.getPositiveText().toString(), Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                }
                            }).show();
                    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            dialog.dismiss();
                        }
                    });
                }
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }
    }
    public class MyHolder extends RecyclerView.ViewHolder {

        ImageView img;
        TextView shop,name,describe,price,standard;
        public MyHolder(@NonNull View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.img);
            shop = itemView.findViewById(R.id.brade);
            name = itemView.findViewById(R.id.name);
            describe = itemView.findViewById(R.id.describe);
            price = itemView.findViewById(R.id.price);
            standard = itemView.findViewById(R.id.standard);
        }
    }
    public class MyAdapter2 extends RecyclerView.Adapter<MyHolder2>{//分类RecyclerView的Adapter

        @NonNull
        @Override
        public MyHolder2 onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.fenlei_item,parent,false);
            MyHolder2 myHolder2 = new MyHolder2(view);
            return myHolder2;
        }

        @Override
        public void onBindViewHolder(@NonNull final MyHolder2 holder, int position) {
            String s = listCategory.get(position);
            holder.text.setText(" "+s+" ");
            //if(position==0) holder.text.setTextSize(20);

        }

        @Override
        public int getItemCount() {
            return listCategory.size();
        }
    }
    public class MyHolder2 extends  RecyclerView.ViewHolder{
        TextView text;
        public MyHolder2(@NonNull View itemView) {
            super(itemView);
            text = itemView.findViewById(R.id.context);
        }
    }

    public String getSearch(String url) throws IOException{
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Response response = client.newCall(request).execute();
        if(response.isSuccessful()){
            String res = response.body().string();
            return res;
        }else{
            throw new IOException("Unexpected code " + response);
        }
    }
    public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder>{

        @NonNull
        @Override
        public SearchViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.serach_res,parent,false);
            SearchViewHolder searchViewHolder = new SearchViewHolder(view);
            return searchViewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull SearchViewHolder holder, int position) {
            holder.brand.setText(searchList.get(position).brand);
            holder.name.setText(searchList.get(position).name);
            holder.des.setText(searchList.get(position).description);
            holder.price.setText(String.valueOf(searchList.get(position).saleMoney));
            Glide.with(getActivity()).load(searchList.get(position).img).into(holder.img);
        }

        @Override
        public int getItemCount() {
            return searchList.size();
        }
    }
    public class SearchViewHolder extends RecyclerView.ViewHolder{

        TextView brand,name,des,price;
        ImageView img;
        public SearchViewHolder(@NonNull View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.imageView22);
            brand = itemView.findViewById(R.id.textView46);
            name = itemView.findViewById(R.id.textView47);
            des = itemView.findViewById(R.id.textView48);
            price = itemView.findViewById(R.id.textView52);
        }
    }
    public static String post1(String url,String json) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Log.i("json:",json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String res = response.body().string();
            Log.i("返回结果：", res);
            return res;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    public String post(String url, String json) throws IOException {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON,json);
        //Log.i("json:",json);
        //SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user",getActivity().MODE_PRIVATE);
        //String token = sharedPreferences.getString("token",null);
        Log.i("token值",token);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("authorization",token)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String res = response.body().string();
            Log.i("返回结果：", res);
            return res;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }
}
